#### LIBRARIES ####
library(tidyverse)
library(readstata13)
library(ggrepel)

#### IMPORT ####
ess8 <- read.dta13("Data/ESS8e01.dta",convert.factors = F)
codes <- read.csv("Data/countrycodes.csv")
essturnout <- read.csv("Data/essturnout.csv")

#### CLEAN ####
codes <- codes%>%
  rename(ccode=ISO3166.1.numeric,
         cntry=ISO3166.1.Alpha.2)%>%
  select(ccode,cntry,name)

essmeans <- ess8%>%
  rename(partisan=clsprty)%>%
  mutate(partisan=replace(partisan,which(partisan==2L),0L))%>%
  mutate(partisan=replace(partisan, which(partisan>2L),NA))%>%
  filter(!is.na(partisan))%>%
  filter(!is.na(pweight))%>%
  group_by(cntry)%>%
  summarise(partmean=weighted.mean(partisan,pweight))

essmeans <- essmeans%>%
  left_join(codes,by="cntry")%>%
  select(cntry,name,partmean)

essmeans <- essmeans%>%
  left_join(essturnout,by="cntry")%>%
  select(cntry,name,partmean,turnout)

#### FIGURE 1 ####
ggplot(essmeans,aes(y=turnout,x=partmean))+
  geom_hline(yintercept = mean(essmeans$turnout,na.rm=T),color="gray50")+
  geom_vline(xintercept = mean(essmeans$partmean,na.rm=T),color="gray50")+
  xlab("Partisanship (ESS)")+
  ylab("Turnout (Last National Election)")+
  geom_point()+
  geom_text_repel(aes(label=name))+
  theme_bw()

 ggsave("Figures/Fig1.pdf",width=6,height=4)

